<template>
  <el-cascader
          v-model="optionValue"
          placeholder="Please choose"
          change-on-select
          clearable
          :options="options"
          :props = "defaultProps">
  </el-cascader>
</template>
<script>
  import { getNodeParentPath } from '../../libs/util'
  import { getCategoryList } from '../../api/pCategory'

  export default {
    name: 'petCategoryCascader',
    props: {
      cId: {
        type: Number,
        default: 0,
      },
        refresh: String,
        editRefresh:String,
    },
    data () {
      return {
        options:[],
        optionValue: [],
        defaultProps: {
          children: 'children',
          label: 'name',
          value: "id"
        }
      }
    },
    methods: {
      setDefault(cId) {
        let path = {}
        getNodeParentPath(cId, this.options, path)
        this.optionValue = [...path.ids, cId]
      },
      requestData() {
          getCategoryList().then( response => {
              this.options = response.data.data
          })
      }
    },
      mounted() {
      this.requestData()
    },
    watch: {
      optionValue (ids) {
        let id = ids[ids.length - 1]
        let cId = id > 0 ? id : 0

        this.$emit("update:cId", cId);
      },
      cId(val) {
        if (val > 0) {
          this.setDefault(this.cId)
        } else {
            this.optionValue = []
        }
      },
      options() {
        if (this.cId) {
          this.setDefault(this.cId)
        }
      },
        refresh() {
            this.requestData()
            this.optionValue = []
        },
        editRefresh() {
            this.requestData()
        }
    }
  }
</script>
